package temp;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
/**
 * A class to show how you can use double buffering because I always forget how.
 * @author Erik
 *
 */
public class Drawing extends JFrame { 
	private static final long serialVersionUID = 1L;
	BufferedImage img;
	int timeStep = 20;
	static Canvas can;
	public static void main(String[] args) {
		Drawing d = new Drawing();
		d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//Need to have a visible parent component to create a buffer strategy
		d.setVisible(true);
		can = new Canvas();
		d.add(can);
		can.createBufferStrategy(2);
		can.setSize(200, 200);
		//d.setResizable(false);
				
		//Create a black background image that are used later
		d.img = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = (Graphics2D) d.img.getGraphics();
		g.setColor(Color.black);
		g.fillRect(0, 0, 200, 200);
		g.dispose();
		//End create image
		
		while(true) {
			//Not until here is anything drawn
			d.drawStuff();
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	private void drawStuff() {
		BufferStrategy bf = can.getBufferStrategy();
		Graphics2D g = null;
		g = (Graphics2D) bf.getDrawGraphics();
		g.drawImage(img,0,0,this);
		g.setColor(Color.red);
		g.drawRect(timeStep, timeStep, 50, 50);
		timeStep++;
		if(timeStep > 200)
			timeStep = 20;
		g.dispose();
		bf.show();
	}
}
